
<template>
  <div id="app">
    <div id="Map" ref="mapObj"></div>
  </div>
</template>

<script>
import "ol/ol.css";
import TileLayer from "ol/layer/Tile";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import XYZ from "ol/source/XYZ";
import { Map, View, Feature, ol } from "ol";
import { Style, Icon } from "ol/style";
import { Point } from "ol/geom";
import { defaults as defaultControls } from "ol/control";
import { fromLonLat } from "ol/proj";


import { onMounted, ref } from "vue";
import areaGeo from "@/assets/bianjie.json";


export default {
  name: "shadow",
  setup() {
    let map = null;
    let mapObj = ref(null);

    const initMap = () => {
      map = new Map({
        target: "Map",
        controls: defaultControls({
          zoom: true
        }).extend([]),
        layers: [
          new TileLayer({
            source: new XYZ({
              url:
                "http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}"
            })
          })
        ],
        view: new View({
          center: fromLonLat([108.522097, 37.272848]),
          zoom: 4.7,
          maxZoom: 19,
          minZoom: 4
        })
      });
    }
    let pointLayer = null;
    let featuresArr = [];

    const addPoints = (coordinates) => {
      // 设置图层
      pointLayer = new VectorLayer({
        source: new VectorSource()
      });
      // 添加图层
      map.addLayer(pointLayer);
      // 循环添加feature
      for (let i = 0; i < coordinates.length; i++) {
        // 创建feature，一个feature就是一个点坐标信息
        let feature = new Feature({
          geometry: new Point(
            fromLonLat([coordinates[i].x, coordinates[i].y])
          )
        });
        feature.setStyle(getIcon(coordinates[i].type));
        featuresArr.push(feature);
      } // for 结束
      // 批量添加feature
      pointLayer.getSource().addFeatures(featuresArr);
    }

    const getIcon = (type) => {
      let src = "";
      type == "bule"
        ? (src = require("../assets/123.gif"))
        : (src = require("../assets/logo.png"));
      var styleIcon = new Style({
        // 设置图片效果
        image: new Icon({
          src: src,
          anchor: [1, 1]
        })
      });
      return styleIcon;
    }

    onMounted(() => {
      initMap();//初始化地图方法
      let coordinates = [
        { x: "106.918082", y: "31.441314", type: "lv" },
        { x: "86.36158200334317", y: "41.42448570787448", type: "bule" },
        { x: "89.71757707811526", y: "31.02619817424643", type: "lv" },
        { x: "116.31694544853109", y: "39.868508850821115", type: "bule" },
        { x: "103.07940932026341", y: "30.438580338450862", type: "lv" }
      ];
      addPoints(coordinates);//根据坐标点批量打点

    })

    return {
      mapObj
    }
  }
};
</script>

<style lang='scss' scoped>
#app,
#Map {
  height: 90vh;
}
</style>
